import axios from 'axios';
import qs from 'qs';
import Vue from 'vue'
import router from '../router'
import url from './Constance'

axios.defaults.baseURL = url.baseUrl; // 本地
axios.defaults.timeout = 30000;

axios.interceptors.request.use(config => {
    config.headers = {
        'Content-Type': 'application/json;charset=UTF-8',
    };
    if(Vue.ls.get("userInfo", '')){
        config.headers.Authorization = Vue.ls.get("userInfo", '').token;
    }
    return config;
}, function (err) {
    return Promise.reject(err);
});

axios.interceptors.response.use(response => {
    if (response.code === 1 || response.data.code === 1) {
        console.log(response)
    }
    if (response.errorCode === '50008' || response.data.errorCode === '50008') {
        Vue.ls.remove('userInfo');
        router.push({path: '/login'});
    }
    return response
}, error => {
    return Promise.reject(error)
})


/**
 * 封装get方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function fetch(url, params = {}) {
    if (!params && typeof (params) != 'undefined' && params != 0) {
        url = url + "?" + qs.stringify(params);
    }

    return new Promise((resolve, reject) => {
        axios.get(url)
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.patch(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */
export function put(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.put(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}
